/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/* prgram code for renewing resource */
package pacificlms.MainPanel;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import pacificlms.LoggedMember;
import pacificlms.DataHolder;
import pacificlms.MasterConnection;
import pacificlms.Verifiable.Database.*;
import pacificlms.Verifiable.VerifiableObject;

/**
 *
 * @author Yasir Tanveer
 */
public class ActionRenewCopyofResource extends CentralUIPanel
{
    /**
     * Creates new form ActionRenewCopyofResource
     */
    public ActionRenewCopyofResource() {
        super(null);
        initComponents();
        
        FillCheckoutList();
    }

    void FillCheckoutList()
    {
        // displays checkout resources of logged in member
        try
        {
            DefaultListModel ListModel=new DefaultListModel();
            Connection con = MasterConnection.getInstance();

            if(LoggedMember.getInstance().IsNonmember())
            {
                JOptionPane.showMessageDialog(null, "Non member can't check out resource, please login first.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                return;

            }
            else
            {

                Statement stmt = con.createStatement();
                Member member=LoggedMember.getInstance();
                CheckOut checkout = new CheckOut();
                checkout.IdentityNumber(member.IdentityNumber(null));
                checkout.Finished("0");
                String SQL =checkout.FindIdenticalSQL();
                ResultSet rs=stmt.executeQuery(SQL);
                while(rs.next())
                {
                    if(rs.getString("CopyStatus").equals("checked out"))
                    {
                        CheckOut CO=new CheckOut();
                        CO = (CheckOut)VerifiableObject.CreateFromResultSet(CheckOut.class, rs, rs.getMetaData());
                        ListModel.addElement(CO);
                    }
                }
                lstCheckouts.setModel(ListModel);
            }

        }
        catch(Exception Ex)
        {
            JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    @Override
    public String TabName()
    {
        return "Renew";
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstCheckouts = new javax.swing.JList();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(615, 535));

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 22)); // NOI18N
        jLabel10.setText("Renew Resource");

        jLabel11.setText("List of Checked Out Resources");

        jScrollPane1.setViewportView(lstCheckouts);

        jButton5.setText("Renew");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RenewAction(evt);
            }
        });

        jButton6.setText("Cancel");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CloseAction(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel11)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 190, Short.MAX_VALUE)
                .addComponent(jButton6)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    //add checkout items which we want to renew 
    int NumOfAvailableCopy(String ResourceCO)
    {
    try
        {
            Connection con = MasterConnection.getInstance();
            Statement stmt = con.createStatement();
            String ResourceCode = ResourceCO;
            int CopyCount, CheckOutCount, HoldCount;
            String SQL = "SELECT Count(*) AS CopyCount FROM copy C WHERE C.resourcecode = '"+ResourceCode+"' AND C.CopyStatus = 'available'";
            String SQL1 = "SELECT Count(*) AS CheckOutCount FROM CheckOut CO WHERE CO.resourcecode ='"+ ResourceCode+ "' AND CO.Finished = '0'";
            String SQL2 = "SELECT Count(*) AS HoldCount FROM hold H  WHERE  H.resourcecode ='"+ ResourceCode+ "' AND H.Finished = '0'";
            
            ResultSet RS = stmt.executeQuery(SQL);
            RS.next();
            CopyCount = RS.getInt("CopyCount");
            
            RS = stmt.executeQuery(SQL1);
            RS.next();
            CheckOutCount = RS.getInt("CheckOutCount");
            
            RS = stmt.executeQuery(SQL2);
            RS.next();
            HoldCount = RS.getInt("HoldCount");
            
            return CopyCount-CheckOutCount-HoldCount;
        }
        catch(Exception Ex)
        { 
            JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
            return 999;
        }
}
    void Renew()
    {
        try
        {
            Object[] values;  
            CheckOut CO = new CheckOut();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            String EndDate;
            Connection con = MasterConnection.getInstance();
            Statement stmt = con.createStatement();
            CourseReserve Reserve = new CourseReserve();
            values=lstCheckouts.getSelectedValues();
            for(int i=0;i<values.length;i++) 
            {
                CO=(CheckOut)values[i];
                Reserve.ResourceCode(CO.ResourceCode(null));
                if(Reserve.IsReserved())
                {
                    JOptionPane.showMessageDialog(null, "This resource has been reserved. You can't Renew.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if(NumOfAvailableCopy(CO.ResourceCode(null))<0)
                {
                    JOptionPane.showMessageDialog(null, "This resource has been put on hold. You can't Renew.", "Validation Warning", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                EndDate = CO.DueDate(null);
                c.setTime(sdf.parse(EndDate));
                c.add(Calendar.DATE, 14);  // number of days to add
                EndDate = sdf.format(c.getTime());
                CO.DueDate(EndDate);
                int RenewalCount;
                RenewalCount = Integer.parseInt(CO.RenewalCount(null));
                CO.RenewalCount(String.valueOf(RenewalCount+1));
                if (!CO.Verify())
                {
                    JOptionPane.showMessageDialog(null, "Error unable to renew", "Database Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                stmt.executeUpdate(CO.UpdateRecrodSQL());
                FillCheckoutList();
                JOptionPane.showMessageDialog(null, "Copy has been renewed successfully", "Success", JOptionPane.INFORMATION_MESSAGE);

            }
        }
        catch(Exception Ex)
        {
            JOptionPane.showMessageDialog(null, "Database error, please try again later\n" + Ex.getMessage(), "Database Error", JOptionPane.ERROR_MESSAGE);
        }
               
    }
       

     
    private void RenewAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenewAction
        Renew();
        
    }//GEN-LAST:event_RenewAction

    private void CloseAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseAction
    Close();        // TODO add your handling code here:
    }//GEN-LAST:event_CloseAction
      
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lstCheckouts;
    // End of variables declaration//GEN-END:variables
}
